import React, { useEffect } from 'react';
import { connect } from 'umi';
import { Tabs } from 'antd';
import _ from 'lodash';

import { PageLoading } from '@/components/index.js';
import { TRDefault } from '@/components/index.js';
import { useTRState } from '#/utils/trHooks.jsx';
import { HttpCode } from '#/utils/contacts.js';

import PriceForecast from './PriceForecast'; // 价差预测
import PriceHistory from './PriceHistory'; // 历史
import AnalysisOfPriceDiff from './AnalysisOfPriceDiff'; // 价差成因分析
import { queryProvinceList } from './services.js';
import { buildPower, getTreeByCodes } from '@/utils';

const { TabPane } = Tabs;

const SpotPriceDiffForecast = ({ menuCode = '', buttonPermissions = [] }) => {
  const [state, setState] = useTRState({
    error: '',
    loading: true,
    power: [], // 数据权限
  });

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    setState({ loading: true });
    let error = '';
    let power = [];
    const res = await queryProvinceList(menuCode);
    if (res?.statusCode === HttpCode.SUCCESS) {
      power = getTreeByCodes(['market', 'group', 'station'], res.json).treeOptions;
      power = power.map((x) => ({
        ...x,
        children: _.flatten(x.children.map((y) => y.children)),
      }));
    } else {
      error = res?.message;
    }
    setState({
      error,
      power,
      loading: false,
    });
  };

  if (state.loading) return <PageLoading />;
  if (state.error) return <TRDefault type="error" message={state.error} />;
  if (!state.power.length) return <TRDefault type="lock" />;
  return (
    <div className={'tabPage'}>
      <Tabs defaultActiveKey={'1'}>
        <TabPane tab="价差预测" key="1">
          <PriceForecast power={state.power} buttonPermissions={buttonPermissions} />
          <PriceHistory power={state.power} buttonPermissions={buttonPermissions} />
        </TabPane>
        <TabPane tab="价差成因分析" key="2">
          <AnalysisOfPriceDiff power={state.power} buttonPermissions={buttonPermissions} />
        </TabPane>
      </Tabs>
    </div>
  );
};

export default connect(({ global }) => ({
  menuCode: global?.configure?.menuCode,
  buttonPermissions: global?.configure?.buttonPermissions,
}))(SpotPriceDiffForecast);
